package com.atguigu.flink.timer;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.TimerService;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Created by Smexy on 2023/2/1
 *
 */
public class Demo2_EventTimeTimer
{
    public static void main(String[] args) {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //创建水印生成策略
        WatermarkStrategy<WaterSensor> watermarkStrategy = WatermarkStrategy
            .<WaterSensor>forMonotonousTimestamps()
            .withTimestampAssigner((e, ts) -> e.getTs());

        env.setParallelism(1);

                env
                   .socketTextStream("hadoop103", 8888)
                   .map(new WaterSensorMapFunction())
                   .assignTimestampsAndWatermarks(watermarkStrategy)
                   .keyBy(WaterSensor::getId)
                   .process(new KeyedProcessFunction<String, WaterSensor, String>()
                   {
                       //定时器触发时指定逻辑
                       @Override
                       public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
                           System.out.println("触发了:" + ctx.getCurrentKey() + "在" +timestamp+" 的定时器，预警...");

                       }

                       long time = 0l;
                       @Override
                       public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                           TimerService timerService = ctx.timerService();

                           if (value.getVc() > 30){
                               //获取当前数据的事件时间，延迟5s
                               time = ctx.timestamp() + 5000;
                               //指定定时器
                               timerService.registerEventTimeTimer(time);
                               System.out.println(ctx.getCurrentKey()+"指定了定时器:"+time);
                           }else{
                               if (value.getVc() <= 10){
                                   //删除定时器
                                   timerService.deleteEventTimeTimer(time);
                                   System.out.println(ctx.getCurrentKey()+"删除了定时器:"+time);
                               }
                           }

                           out.collect(value.toString());
                       }
                   })
                   .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
    }
}
